package com.atguigu.gmall.common.service;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.entity.GmallCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

@Component
public class RabbitService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    //发消息
    public boolean sendMessage(String exchange ,String routingKey , Object message){
        GmallCorrelationData gmallCorrelationData = retryMessageData(exchange,routingKey,message);
        rabbitTemplate.convertAndSend(exchange,routingKey,message,gmallCorrelationData);
        return true;
    }


    private GmallCorrelationData retryMessageData(String exchange, String routingKey, Object message) {
        GmallCorrelationData gmallCorrelationData = new GmallCorrelationData();
        String uuid = UUID.randomUUID().toString();
        gmallCorrelationData.setId(uuid);
        gmallCorrelationData.setMessage(message);
        gmallCorrelationData.setRoutingKey(routingKey);
        gmallCorrelationData.setExchange(exchange);

        redisTemplate.opsForHash().put("rabbit_prefix",uuid, JSONObject.toJSONString(gmallCorrelationData));
        return gmallCorrelationData;
    }

    //死信
    public void sendDeadLetterMessage(Object msg  ,String exchange ,String routingKey ,int dalayTime){
        GmallCorrelationData gmallCorrelationData = retryMessageData(exchange, routingKey, msg);
        gmallCorrelationData.setDelay(true);
        gmallCorrelationData.setDelayTime(dalayTime);
        rabbitTemplate.convertAndSend(exchange,routingKey,msg,message -> {
            System.out.println("发送消息的时间：" + new Date());
            message.getMessageProperties().setExpiration(String.valueOf(dalayTime*1000));
            return message;
        },gmallCorrelationData);
    }

    //发延迟消息 （基于插件的）
    public void sendDelayMessage(String exchange, String routingKey, Object msg,int delayTime){
        GmallCorrelationData correlationData  = retryMessageData(exchange, routingKey, msg);
        //是延迟消息
        correlationData.setDelay(true);
        //延迟的时间
        correlationData.setDelayTime(delayTime);
        //延迟消息
        rabbitTemplate.convertAndSend(exchange,routingKey,msg,message -> {
            System.out.println("发送消息的时间：" + new Date());
            message.getMessageProperties().setDelay(delayTime*1000);
            return message;
        },correlationData);
    }
}
